<!--
 * @Description: zzb
 * @Version: 0.0.1
 * @Autor: zzb
 * @Date: 2021-11-25 11:18:33
 * @LastEditors: zzb
 * @LastEditTime: 2023-02-17 16:56:06
-->
<template>
  <div class="content">
    <Resize>
      <template v-slot:left>
        <div class="content_l">
          <div class="left-btn">
            <vxe-toolbar v-if="false">
              <template #buttons>
                <el-button
                  type="cyan"
                  size="mini"
                  plain
                  @click="$refs.xTree.setAllTreeExpand(true)"
                  >全部展开</el-button
                >
                <el-button
                  type="cyan"
                  size="mini"
                  plain
                  @click="$refs.xTree.clearTreeExpand()"
                  >全部关闭</el-button
                >
                <el-button
                  type="cyan"
                  size="mini"
                  plain
                  @click="getSiteList"
                  v-if="siteRow"
                  >返回站点</el-button
                >
                <!-- <vxe-button @click="getSiteList">返回站点</vxe-button> -->
              </template>
            </vxe-toolbar>
            <vxe-toolbar>
              <template #buttons>
                <vxe-radio-button
                  v-model="value7"
                  :label="true"
                  v-if="false"
                  :content="value7 ? '全部关闭' : '全部展开'"
                  :strict="false"
                  size="mini"
                  :disabled="!siteRow"
                ></vxe-radio-button>
                <vxe-button
                  size="mini"
                  @click="getSiteList"
                  :disabled="!siteRow"
                  >返回站点</vxe-button
                >
                <!-- <vxe-button @click="getSiteList">返回站点</vxe-button> -->
              </template>
            </vxe-toolbar>

            <vxe-toolbar style="height: 40px; width: 100%" v-if="isShowChannel">
              <template #buttons>
                <vxe-input
                  v-model="filterName"
                  type="search"
                  clearable
                  size="small"
                  placeholder="栏目名称、栏目Id"
                  @keyup="handleTemplateQuery"
                  style="display: block; width: 90%; margin: 0 auto"
                ></vxe-input>
              </template>
            </vxe-toolbar>
          </div>
          <vxe-table
            :loading="leftTableLoading"
            :loading-config="{ icon: 'el-icon-loading' }"
            highlight-current-row
            highlight-hover-row
            row-key
            :show-header="false"
            show-overflow
            ref="xTree"
            border="inner"
            :data="siteList"
            :tree-config="{
              children: 'children',
              transform: false,
              parentKey: 'parentId',
              line: true,
              iconOpen: 'el-icon-remove',
              iconClose: 'el-icon-circle-plus',
            }"
            class="left-table"
            @cell-click="clickListRow"
          >
            <vxe-column tree-node field="name" title="Name111" show-overflow>
              <template #default="{ row }">
                <span>
                  <span
                    v-if="(row.id || row.siteId) == currentRowId && !row.root"
                    class="activeRow"
                  >
                    <svg-icon icon-class="right" style="color: #009a94" />
                  </span>
                  <!-- 电脑 -->
                  <img
                    src="../../../assets/icons/png/Display Check.png"
                    alt=""
                    style="vertical-align: text-bottom"
                    v-if="row.root == '000'"
                  />
                  <!-- 地球 -->
                  <img
                    src="../../../assets/icons/png/globe.gif"
                    alt=""
                    style="vertical-align: bottom"
                    v-if="!row.id && row.root != '000'"
                  />

                  <!-- 文件夹 -->
                  <img
                    src="../../../assets/icons/png/folder.gif"
                    alt=""
                    style="vertical-align: text-top"
                    v-if="row.id"
                  />

                  <!-- 小箭头 -->
                  <img
                    src="../../../assets/icons/png/contextMenu.gif"
                    alt=""
                    v-if="row.siteId && (row.id || row.root)"
                    @click.stop="openMenu(row, $event)"
                  />

                  <span style="cursor: pointer; fontsize: 12px; color: #000">
                    {{ row.name }}</span
                  >
                </span>
              </template>
            </vxe-column>
          </vxe-table>
          <!-- <LeftTree :node='node' @handleOnRightClick="openMenu($event)" @fo='fo'></LeftTree> -->
        </div>
      </template>
      <template v-slot:right>
        <div class="content_r">
          <template v-if="showTemTab">
            <vxe-toolbar style="height: 40px; padding: 0 10px">
              <template #buttons>
                <vxe-input
                  v-model="fileName"
                  type="search"
                  clearable
                  size="small"
                  placeholder="模板名称、模板Id"
                  @keyup="handleFileQuery()"
                  style="display: block; width: 100%"
                  ref="fileNameRef"
                ></vxe-input>
              </template>
            </vxe-toolbar>
            <el-table
              v-loading="tableLoading"
              :data="templateList"
              style="width: 100%"
              v-if="showTemTab"
              size="mini"
            >
              <el-table-column prop="info" align="center" label="模板名称">
              </el-table-column>
              <el-table-column
                prop="id"
                align="center"
                label="模板ID"
                width="120"
              >
              </el-table-column>
              <el-table-column
                prop="updateDate"
                align="center"
                width="180"
                label="更新时间"
                show-overflow-toolti
              >
              </el-table-column>
              <el-table-column
                prop="createdDate"
                align="center"
                width="180"
                label="创建时间"
                show-overflow-toolti
              >
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                width="240"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="scope" v-if="scope.row.userId !== 1">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-news"
                    @click="handlePreview(scope.row)"
                    v-hasPermi="['system:template:view']"
                    >预览</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleEdit(scope.row)"
                    v-hasPermi="['system:template:edit']"
                    >编辑</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDel(scope.row)"
                    v-hasPermi="['system:template:delete']"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>

          <span v-else class="null">
            <!-- “模板管理”是 WYCMS系统的主要功能模块。它将完成网站、栏目模板的新建 、编辑与删除等功能。左侧菜单显示该平台下所支持的网站及栏目的模板信息，超级管理员将能看到全部网站及栏目的模板，其它用户随着角色不同将看到属于自己权限的内容。 -->
            <svg-icon icon-class="null" />
          </span>
        </div>
      </template>
    </Resize>
    <ul
      v-show="addFile"
      :style="{ left: left + 'px', top: top + 'px' }"
      class="contextmenu"
    >
      <li @click="handleAddFile" v-hasPermi="['system:template:add']">
        新建文件夹
      </li>
      <li @click="handlePublic('net')" v-hasPermi="['system:publicize:site']">
        网站发布
      </li>
      <li @click="haldleSeeNet">网站浏览</li>
      <li @click="haldleClearCache">清除缓存</li>
    </ul>
    <ul
      v-show="addTemplate"
      :style="{ left: left + 'px', top: top + 'px' }"
      class="contextmenu"
    >
      <li @click="handleAddTemplate" v-hasPermi="['system:template:add']">
        新建模板
      </li>
      <li @click="handleFileAttr" v-hasPermi="['system:template:edit']">
        文件夹属性
      </li>
      <li @click="handleFileDel" v-hasPermi="['system:template:delete']">
        删除文件夹
      </li>
    </ul>
    <!-- 添加或修改文件夹对话框 -->
    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="160px"
        @submit.native.prevent
      >
        <el-form-item label="模板文件夹名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入模板文件夹名称"
            maxlength="30"
          />
        </el-form-item>
        <span>只能输入中文和英文字符，最多可以输入10个字符</span>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 栏目发布   站点发布 -->
    <el-dialog
      v-dialogDrag
      :title="publicDialog.title"
      :visible.sync="publicDialog.open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <strong style="fontsize: 24px; color: red; margin: 0 0 10px 0"
        >请选择您要进行的操作:</strong
      >

      <div class="grid-content" style="padding-left: 10px">
        <el-row class="grid-content">
          <el-radio v-model="radio1" :label="0" style="width: 100%"
            >只发布站点首页</el-radio
          >
        </el-row>
        <el-row class="grid-content">
          <el-radio v-model="radio1" :label="1" style="width: 100%"
            >发布站点及其所有栏目(后台)</el-radio
          >
        </el-row>
        <el-row class="grid-content">
          <el-radio v-model="radio1" :label="2" style="width: 100%"
            >只发布站点下的已发布文章(最近
            <el-input class="radio_input" v-model="dayNum2"></el-input>
            天)(后台)
          </el-radio>
        </el-row>
        <el-row class="grid-content">
          <el-radio v-model="radio1" :label="3" style="width: 100%"
            >发布站点及其所有栏目(含最近
            <el-input class="radio_input" v-model="dayNum3"></el-input>
            天的所有已发布文章)(后台)
          </el-radio>
        </el-row>
      </div>

      <template v-if="loading">
        <span style="color: rgb(255, 0, 0)">
          发布中,请稍后。如果您不需要确认发布结果，可以点击“隐藏窗口”按钮使发布转入后台执行，您可以并行的处理其他事务。
        </span>
        <i class="el-icon-loading"></i>
      </template>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">隐藏窗口</el-button>
        <el-button
          slot="reference"
          type="primary"
          @click.enter="submitForm_channel"
          :disabled="loading"
          >确定发布</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { makeSiteViewUrl } from "@/api/content/clounm";
import {
  listTemplate,
  listTemplateFile,
  delTemplate,
  delTemplateFile,
  TemplateFileInfo,
  updateFileInfo,
  addFileInfo,
  viewTemplate,
} from "@/api/template/index";
import { listSite, publicSite } from "@/api/content/net";
import { clearPublishCache } from "@/api/useful";
import { objectMerge } from "@/utils/index";
import { refreshRouteArr } from "@/settings.js";

import { debounce } from "@/utils";
export default {
  name: "TemplateMenu",
  data() {
    return {
      //左侧栏目筛选
      filterName: "",
      // 右侧文件筛选
      fileName: "",
      isShowChannel: false,
      tableLoading: false,
      //全部展开 全部关闭
      value7: false,
      left: 0,
      top: 0,
      //左侧站点列表
      siteList: [],
      siteListCache: [],
      //ul  模板行 图标  新建模板
      addTemplate: false,
      //ul  root行 图标  新建文件夹
      addFile: false,
      //模板表格
      templateList: [],
      templateListCache: [],
      //row  当前左侧 文件夹
      fileRow: undefined,
      //站点  row
      siteRow: {
        siteId: undefined,
      },
      //添加或修改文件夹对话框
      title: null,
      open: false,
      //文件夹属性表单
      form: {},
      rules: {
        name: [
          { required: true, message: "文件夹名称不能为空", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z\d]+$/,
            message: "只能输入中文、字母、数字，最多可以输入10个字符",
            trigger: "blur",
          },
        ],
      },
      //发布loading
      loading: false,
      leftTableLoading: false,
      //发布对话框   单选按钮
      radio1: 0,
      dayNum1: 30,
      dayNum2: 30,
      dayNum3: 30,
      //发布对话框  title open
      publicDialog: {
        title: null,
        open: false,
        type: null,
      },
      //点击文件夹  显示文件夹模板列表
      showTemTab: false,
    };
  },

  components: {},

  computed: {
    currentRowId() {
      return this.fileRow?.id || this.siteRow?.siteId;
    },
  },

  mounted() {
    this.getSiteList();
    console.log("mouned");
    document.addEventListener("visibilitychange", this.Fnrefresh);
  },

  watch: {
    addFile(value) {
      if (value) {
        document.body.addEventListener("click", this.closeMenu);
      } else {
        document.body.removeEventListener("click", this.closeMenu);
      }
    },
    addTemplate(value) {
      if (value) {
        document.body.addEventListener("click", this.closeMenu);
      } else {
        document.body.removeEventListener("click", this.closeMenu);
      }
    },
    value7(value) {
      if (value) {
        this.$refs.xTree.setAllTreeExpand(true);
      } else {
        this.$refs.xTree.clearTreeExpand();
        //展开第一个节点
        this.$nextTick(() => {
          this.$refs.xTree.setTreeExpand(this.siteList[0], true);
        });
      }
    },
  },

  methods: {
    Fnrefresh() {
      let route = this.$route.path;

      if (!document.hidden) {
        if (refreshRouteArr.includes(route)) {
          this.fileRow && this.haldleClickFile();
        }
      }
    },
    //获取站点列表
    getSiteList() {
      this.filterName = "";
      this.siteRow = undefined;
      this.fileRow = undefined;
      this.value7 = false;
      this.showTemTab = false;
      this.templateList = [];
      this.templateListCache = [];

      this.leftTableLoading = true;
      listSite()
        .then((res) => {
          this.siteList = [
            { name: "模板库-站点列表", root: "000", children: res.data },
          ];
        })
        .then(() => {
          //展开第一个节点
          this.$nextTick(() => {
            this.$refs.xTree.setTreeExpand(this.siteList[0], true);
            this.leftTableLoading = false;
          });
        });
    },
    //获取模板列表
    clickListRow({ row }) {
      if (row.siteId && row.id) {
        this.showTemTab = true;
        this.fileRow = row;
        this.haldleClickFile();
      } else if (!row.root) {
        this.showTemTab = false;
        this.siteRow = row;
        this.$store.dispatch("column/setSiteRow", row);
        this.haldleClickSite();
      }
    },
    //点击站点  获取当前站点的文件
    haldleClickSite() {
      console.log("this.siteRow: ", this.siteRow);
      this.leftTableLoading = true;
      this.siteList[0].children = [];
      listTemplateFile({ siteId: this.siteRow.siteId })
        .then((res) => {
          this.siteListCache = res.data;
          console.log("this.siteListCache: ", this.siteListCache);
          this.channelQuery();
          this.isShowChannel = true;
        })
        .then(() => {
          //展开第一个节点
          this.$nextTick(() => {
            this.$refs.xTree.setTreeExpand(this.siteList[0], true);
          });
        });
    },
    //点击文件夹
    haldleClickFile() {
      this.tableLoading = true;
      this.fileName = "";
      listTemplate({ parentId: this.fileRow.id }).then((res) => {
        this.templateListCache = res.data;
        this.channelFileQuery();
        this.$refs.fileNameRef.focus();
        this.tableLoading = false;
      });
    },
    //网站浏览
    haldleSeeNet() {
      makeSiteViewUrl({ siteAlias: this.siteRow.alias }).then((res) => {
        let href = res.msg;
        window.open(href, "_blank");
      });
    },
    // 清除模板缓存
    haldleClearCache() {
      clearPublishCache({ siteAlias: this.siteRow.alias }).then((res) => {
        if (res.code == 200) {
          this.msgSuccess("清除缓存成功");
        }
      });
    },
    handlePublic(type) {
      this.publicDialog = {
        open: true,
        title: "网站栏目",
        type: "net",
      };
    },
    handleTemplateQuery: debounce(function () {
      this.channelQuery();
    }, 600),
    channelQuery() {
      new Promise((resolve, reject) => {
        let aa = this.siteListCache.filter((item) => {
          return this.filterName
            ? item.name.indexOf(this.filterName.trim().toLowerCase()) > -1
            : true;
        });
        console.log("aa: ", aa);

        this.siteRow.children = aa;
        this.siteRow.root = "111";

        this.siteList = [this.siteRow];
        this.leftTableLoading = false;

        resolve();
      }).then(() => {
        //展开第一个节点
        this.$nextTick(() => {
          this.$refs.xTree.setTreeExpand(this.siteList[0], true);
        });
      });
    },

    handleFileQuery: debounce(function () {
      this.channelFileQuery();
    }, 600),
    channelFileQuery() {
      new Promise((resolve, reject) => {
        this.templateList = this.templateListCache.filter((item) => {
          console.log("item: ", item);
          // return this.fileName
          //   ? item.info.indexOf(this.fileName.trim().toLowerCase()) > -1 ||
          //       item.id.indexOf(this.fileName.trim().toLowerCase()) > -1
          //   : true;
          if (this.fileName) {
            return (
              item.info.indexOf(this.fileName.trim().toLowerCase()) > -1 ||
              String(item.id).indexOf(this.fileName.trim().toLowerCase()) > -1
            );
          }
          return true;
        });

        resolve();
      });
    },

    //模板编辑
    handleEdit(row) {
      let { href } = this.$router.resolve({
        path: "/template/edit",
        query: {
          siteId: row.siteId,
          id: row.id,
          parentId: this.fileRow.id,
        },
      });
      window.open(href, "_blank");
    },
    //模板预览
    handlePreview(row) {
      let { href } = this.$router.resolve(`/template/view/${row.id}`);
      window.open(href, "_blank");
      // viewTemplate({ templateId: row.id }).then((res) => {
      // });
    },
    //模板删除
    handleDel(row) {
      this.$confirm(
        `您确定要删除模板  ' s${row.info} ' 吗？如果删除，您必须确保同时删除所有栏目对此模板的引用，否则可能会引发异常！`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          delTemplate(row.id).then((res) => {
            this.msgSuccess("删除成功");
            this.haldleClickFile();
          });
        })
        .catch(() => {});
    },
    //新增文件夹
    handleAddFile() {
      this.open = true;
      this.title = "新增文件夹";
      this.reset();
    },
    //新建模板
    handleAddTemplate() {
      let { href } = this.$router.resolve({
        path: "/template/edit",
        query: {
          siteId: this.fileRow.siteId,
          parentId: this.fileRow.id,
        },
      });
      window.open(href, "_blank");
    },
    //文件夹属性
    handleFileAttr() {
      TemplateFileInfo(this.fileRow.id)
        .then((res) => {
          this.form = res.data;
        })
        .then(() => {
          this.open = true;
          this.title = "文件夹属性";
        });
    },
    //文件夹删除
    handleFileDel() {
      this.$confirm(
        "注意:此操作将直接永久删除，包括此文件夹下的所有模板，并且不可以恢复!您确定?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          delTemplateFile(this.fileRow.id).then((res) => {
            if (res.code == 200) {
              this.msgSuccess("删除成功");
            }
            this.haldleClickSite(this.siteRow);
          });
        })
        .catch(() => {});
    },
    //对话框确认
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateFileInfo(this.form).then(() => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.haldleClickSite();
            });
          } else {
            addFileInfo(
              objectMerge(this.form, { siteId: this.siteRow.siteId })
            ).then(() => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.haldleClickSite();
            });
          }
        }
      });
    },
    // 发布对话框   确认按钮
    submitForm_channel() {
      let title = "";
      let form;
      let radio = this.radio1;

      form = {
        siteAlias: this.siteRow.alias,
        type: this.radio1,
        dayNum: 0,
        siteId: this.siteRow.siteId,
      };
      if (radio == 0) {
        title = "您确定只是要发布此站点首页？";
      } else if (radio == 1) {
        title = "您确定要发布此站点及其所有栏目？";
      } else if (radio == 2) {
        title = "您确定要发布此站点的所有文章？";
        form.dayNum = this.dayNum2;
      } else if (radio == 3) {
        title = "您确定要发布此站点及其所有栏目和文章？";
        form.dayNum = this.dayNum3;
      }

      this.$confirm(title, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;

          publicSite(form).then((res) => {
            if (res.code == 200 && this.loading) {
              this.loading = false;
              this.msgSuccess(res.msg);
            } else {
              this.msgSuccess("站点发布成功");
            }
            this.cancel();
          });
        })
        .catch(() => {
          return;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.publicDialog = {
        open: false,
        title: null,
        type: null,
      };
      this.loading = false;
      this.radio1 = 0;
      this.dayNum1 = this.dayNum2 = this.dayNum3 = 30;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    openMenu(row, e) {
      this.closeMenu();
      //高亮当前行
      this.$refs.xTree.setCurrentRow(row);
      const menuMinWidth = 105;
      const menuMinHeight = 100;
      const offsetLeft = this.$el.getBoundingClientRect().left; // container margin left
      const offsetWidth = this.$el.offsetWidth; // container width
      const offsetHeight = this.$el.offsetHeight;
      console.log("🚀 ~ file: index.vue:550 ~ openMenu ~ this.$el", this.$el);
      const maxLeft = offsetWidth - menuMinWidth; // left boundary
      const left = e.clientX + 15; // 15: margin right
      const top = e.clientY;
      const maxHeight = offsetHeight - menuMinHeight;
      if (left > maxLeft) {
        this.left = maxLeft;
      } else {
        this.left = left;
      }
      // this.top = e.clientY + 15;
      this.top = top;
      if (top > offsetHeight) {
        this.top = top - menuMinHeight;
      } else {
        this.top = top;
      }
      if (row.root) {
        //新建文件夹
        this.addFile = true;
        // this.siteRow = row;
      } else if (!row.root && row.siteId && row.id) {
        //新建模板
        this.addTemplate = true;
        this.fileRow = row;
      }
    },
    closeMenu() {
      this.addFile = false;
      this.addTemplate = false;
    },
  },
  destroyed() {
    document.removeEventListener("visibilitychange", this.Fnrefresh);
  },
};
</script>

<style scoped lang="scss">
@import "~@/assets/styles/variables.scss";
.content {
  width: 100%;
  // height: calc(100vh - 100px);
  // height: calc(100vh - #{$footHeight} - 0px - 50px - 20px);
  display: flex;
  flex-direction: row;
  // padding: 10px;
  position: relative;
  border: 1px solid #ccc;
  .content_l {
    // min-width: 240px;
    overflow: auto;
    height: 100%;
    width: 100%;
    // background: #fffbf0 !important;
    display: flex;
    flex-direction: column;
    .left-table {
      flex: 1;
      height: 0;
      overflow: auto;
    }
  }
  .content_r {
    overflow: auto;
    height: 100%;
    width: 100%;
    // padding: 10px;
    border-left: 1px solid #ccc;
    flex: 1;
    display: flex;
    flex-direction: column;
    .null {
      background: #fff;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      .svg-icon {
        width: 50%;
        height: 50%;
      }
    }
  }
}
.radio_input {
  width: 60px;
}
</style>
